import subprocess
import sys
import importlib
import requests
import os

# 检查并安装 requests 库
def ensure_requests_installed():
    try:
        import requests
        print("已检测到 requests 库，继续运行...")
    except ImportError:
        print("未检测到 requests 库，正在尝试安装...")
        try:
            subprocess.check_call([sys.executable, "-m", "pip", "install", "requests"])
            print("requests 库安装成功！")
        except Exception as e:
            print(f"安装 requests 库时出错：{e}")
            sys.exit(1)

# 请求获取核心列表
def get_core_list():
    url = "https://sync.mcsl.com.cn/api/core"
    payload = {}
    headers = {}
    response = requests.request("GET", url, headers=headers, data=payload)
    if response.status_code == 200:
        return response.json()
    else:
        print(f"请求失败，状态码：{response.status_code}")
        return None

# 用户选择核心
def choose_core(core_list):
    print("请选择一个核心：")
    for index, core in enumerate(core_list):
        print(f"{index + 1}. {core}")
    while True:
        try:
            choice = int(input("请输入核心编号："))
            if 1 <= choice <= len(core_list):
                return core_list[choice - 1]
            else:
                print("输入的编号超出范围，请重新输入！")
        except ValueError:
            print("请输入一个有效的数字编号！")

# 请求获取特定核心支持的Minecraft版本列表
def get_core_versions(core_type):
    url = f"https://sync.mcsl.com.cn/api/core/{core_type}"
    payload = {}
    headers = {}
    response = requests.request("GET", url, headers=headers, data=payload)
    if response.status_code == 200:
        return response.json()
    else:
        print(f"请求失败，状态码：{response.status_code}")
        return None

# 用户选择Minecraft版本
def choose_version(version_list):
    print("请选择一个Minecraft版本：")
    for index, version in enumerate(version_list):
        print(f"{index + 1}. {version}")
    while True:
        try:
            choice = int(input("请输入版本编号："))
            if 1 <= choice <= len(version_list):
                return version_list[choice - 1]
            else:
                print("输入的编号超出范围，请重新输入！")
        except ValueError:
            print("请输入一个有效的数字编号！")

# 请求获取特定核心的特定Minecraft版本的构建列表
def get_core_builds(core_type, mc_version):
    url = f"https://sync.mcsl.com.cn/api/core/{core_type}/{mc_version}"
    payload = {}
    headers = {}
    response = requests.request("GET", url, headers=headers, data=payload)
    if response.status_code == 200:
        return response.json()
    else:
        print(f"请求失败，状态码：{response.status_code}")
        return None

# 用户选择构建
def choose_build(build_list):
    print("请选择一个构建：")
    for index, build in enumerate(build_list):
        print(f"{index + 1}. {build}")
    while True:
        try:
            choice = int(input("请输入构建编号："))
            if 1 <= choice <= len(build_list):
                return build_list[choice - 1]
            else:
                print("输入的编号超出范围，请重新输入！")
        except ValueError:
            print("请输入一个有效的数字编号！")

# 请求获取特定构建的详细信息
def get_build_details(core_type, mc_version, core_version):
    url = f"https://sync.mcsl.com.cn/api/core/{core_type}/{mc_version}/{core_version}"
    payload = {}
    headers = {}
    response = requests.request("GET", url, headers=headers, data=payload)
    if response.status_code == 200:
        return response.json()
    else:
        print(f"请求失败，状态码：{response.status_code}")
        return None

# 下载构建
def download_build(download_url, save_path):
    try:
        response = requests.get(download_url, stream=True)
        if response.status_code == 200:
            with open(save_path, "wb") as file:
                for chunk in response.iter_content(chunk_size=1024):
                    if chunk:
                        file.write(chunk)
            print(f"下载完成，文件已保存到：{save_path}")
        else:
            print(f"下载失败，状态码：{response.status_code}")
    except Exception as e:
        print(f"下载过程中出现错误：{e}")
def download():
    ensure_requests_installed()  # 确保 requests 库已安装

    # 获取核心列表并让用户选择一个核心
    core_data = get_core_list()
    if core_data and core_data["code"] == 200:
        core_list = core_data["data"]
        chosen_core = choose_core(core_list)
        print(f"您选择的核心是：{chosen_core}")

        # 获取该核心支持的Minecraft版本列表并让用户选择一个版本
        version_data = get_core_versions(chosen_core)
        if version_data and version_data["code"] == 200:
            version_list = version_data["data"]["versions"]
            chosen_version = choose_version(version_list)
            print(f"您选择的Minecraft版本是：{chosen_version}")

            # 获取该版本的构建列表并让用户选择一个构建
            build_data = get_core_builds(chosen_core, chosen_version)
            if build_data and build_data["code"] == 200:
                build_list = build_data["data"]["builds"]
                chosen_build = choose_build(build_list)
                print(f"您选择的构建是：{chosen_build}")

                # 获取该构建的详细信息
                build_details = get_build_details(chosen_core, chosen_version, chosen_build)
                if build_details and build_details["code"] == 200:
                    build_info = build_details["data"]["build"]
                    print("构建详细信息：")
                    print(f"同步时间：{build_info['sync_time']}")
                    print(f"下载链接：{build_info['download_url']}")
                    print(f"核心类型：{build_info['core_type']}")
                    print(f"Minecraft版本：{build_info['mc_version']}")
                    print(f"构建版本：{build_info['core_version']}")

                    # 提示用户是否下载
                    download_choice = input("是否下载该构建？(y/n): ").strip().lower()
                    if download_choice == "y":
                        download_path = os.path.join(os.getcwd(), f"{chosen_core}-{chosen_version}-{chosen_build}-MCOYA.jar")
                        download_build(build_info["download_url"], download_path)
                    else:
                        print("已取消下载。")
                else:
                    print("无法获取该构建的详细信息，请检查网络或稍后再试！")
            else:
                print("无法获取该版本的构建列表，请检查网络或稍后再试！")
        else:
            print("无法获取该核心支持的Minecraft版本列表，请检查网络或稍后再试！")
    else:
        print("无法获取核心列表，请检查网络或稍后再试！")
